<?php
require_once( '../system/smarty.inc' );
require_once( '../system/tdao/Class_T_MON_CELL.php' );
require_once( '../system/tdao/Class_T_MON_CELL_WEEK.php' );

require_once( '../system/mdao/Class_M_OTHER.php' );
require_once( '../system/Class_ERROR.php' );
require_once( '../system/Class_PWD.php' );
require_once( '../system/login.inc.php' );

Class_PWD::valid_auth(AOKI_AUTH_MON_CELL,$login['staff_auth']);
$dao =  new Class_T_MON_CELL_WEEK;

if( $_SERVER['REQUEST_METHOD'] == 'GET' ){
	$phase = 'input';
	$forms["year4"]    = $_GET['year4'];
	$forms["matrix_cd"]  = $_GET['matrix_cd'];
	if( isset($_GET['id']) && $_GET['id'] != '' ){
		$forms  = $dao->get( $_GET['id'] );
		$forms["id"]       = $_GET['id'];
	}else{
		//$forms['auth'] = 0;
	}
}else{
	$forms = $_POST;
	if( $forms['mode'] == 'input' ){
		$err     = new Class_ERROR;
		$chk     = $dao->get_checks();
		foreach ($chk as $kcol => $chkval) {
			$err_mes[$kcol]  = $err->check( $forms[$kcol], $chkval );
		}
	
		if ( $err->clear ){
			$cols     = $dao->get_cols();
			foreach($cols as $kcol => $val) {
				$values[$kcol] = $forms[$kcol] ;
			}
			
			//桁数チェック
			$maxlens = $dao->get_maxlens();
			foreach ( $maxlens as $k => $v ) {
				$err_mes[$k] =$err->check_size($values[$k], $v);
			}
				
			if( $err_mes['matrix_cd'] == '' ){
				if( $forms['id'] == '' ){
					$where = sprintf(" matrix_cd = '%s'", $forms['matrix_cd'] );
				}else{
					$where = sprintf(" matrix_cd = '%s' AND matrix_cd <> %s", $forms['matrix_cd'], $forms['matrix_cd'] );
				}
				if ( $dao->exits($where) ) {
					$err->clear = false;
					$err_mes['matrix_cd'] = '<p class="error">この週は重複しています</p>';
				}
			}
			
		}	
		
		if( $err->clear ){

			if( $forms['id'] == '' ){
				if ($dao->add0($values)) {
					$smarty->assign('message', '登録が完了しました。');
				} else {
					$smarty->assign('message', '登録が失敗しました。');
				}
			}else{
				
				if ($dao->edit( $forms['id'], $values )) {
					$smarty->assign('message', '更新が完了しました。');
				} else {
					$smarty->assign('message', '更新が失敗しました。');
				}
				$id = $forms['matrix_cd'];
			}


			
			$phase = 'complete';
		}else{
			$phase = 'input';
		}
	}
}

if (empty($forms["year4"])) {
	$forms["year4"] = date('Y');
}
if( isset( $forms ) ) $smarty->assign('forms', $forms);
if( isset( $err_mes ) ) $smarty->assign('err', $err_mes);

if ($phase != 'complete') {
	
}

$smarty->assign('year4',  Class_PWD::get_years());

$week= Class_M_OTHER::get_week_array( $forms["year4"], PLEASE_SELECT_ARR );
$smarty->assign('week', $week );

$smarty->assign('phase', $phase );
$smarty->assign('menu',  $smarty->fetch('menu.html') );
$smarty->assign('logout', $smarty->fetch('logout.html') );
$smarty->assign('footer', $smarty->fetch('footer.html') );

$smarty->display('tmoncell_form.html');
?>